package com.supply.dl.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supply.dl.R;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalPositionAdapter;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.bean.BaseItemBean;
import com.supply.dl.bean.EventBusImage;
import com.supply.dl.bean.JobAttachBean;
import com.supply.dl.bean.JobInfoBean;
import com.supply.dl.bean.MoveDetailBean;
import com.supply.dl.bean.OperateFlagEnum;
import com.supply.dl.bean.OrderInAndOutBoundBean;
import com.supply.dl.bean.PositionInfoBean;
import com.supply.dl.bean.request.SaveJobInfoDetailRequest;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.WorkInfoBean;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.constant.Constants;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.CommonNormalAdapterUtil;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.InterfaceUtil;
import com.supply.dl.utils.RecyclerViewUtil;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.FileUtils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.view.RecycleScrollView;
import com.supply.dl.widget.LoadTipFailedLayout;
import com.supply.dl.widget.adapter.CommonNormalAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 移库发货详情
 * <p>
 * Author: tian <br>
 * Time: 2018/6/13 10:47
 */
public class MoveHouseSendGoodsDetailActivity extends BaseActivity {

    /**
     * activity标识
     */
    private int activityFlag;
    @BindView(R.id.rs)
    RecycleScrollView rs;

    /**
     * 物料列表
     */
    @BindView(R.id.materail_rc)
    MaxRecyclerView materielRecyclerView;


    /**
     * 加载框
     */
    @BindView(R.id.inbound_location_detail_main_loadView)
    LoadTipFailedLayout loadTipFailedLayout;

    /**
     * 为定位
     */
    @BindView(R.id.un_location_tv)
    TextView notLocatedTv;

    @BindView(R.id.unlocation_line)
    View notLocatedLineView;

    /**
     * 已定位
     */
    @BindView(R.id.located_tv)
    TextView hadLocatedTv;

    @BindView(R.id.had_location_line)
    View hadLocatedLineView;

    /**
     * 添加新定位按钮
     */
    @BindView(R.id.add_location_tv)
    TextView addNewPositionBtn;

    /**
     * 批量定位
     */
    @BindView(R.id.location_lot_tv)
    TextView batchPositionBtn;

    /**
     * 定位列表
     */
    @BindView(R.id.location_rc)
    MaxRecyclerView workRecyclerView;


    @BindView(R.id.common_letter_of_notice_info_noticeLetterNoTv)
    TextView orderTitle;
    @BindView(R.id.common_letter_of_notice_info_showNoticeLetterNo)
    TextView orderNo;//移库单号
    @BindView(R.id.common_letter_of_notice_info_positionStatusName)
    TextView orderStatesName;//订单状态
    @BindView(R.id.common_letter_of_notice_info_firstTv)
    TextView creteTimeTitle;
    @BindView(R.id.common_letter_of_notice_info_showFirstValue)
    TextView creteTime;//建单时间
    @BindView(R.id.common_letter_of_notice_info_secondTv)
    TextView moveTypeTitle;
    @BindView(R.id.common_letter_of_notice_info_showSecondValue)
    TextView moveTypeName;//移库类型
    @BindView(R.id.common_letter_of_notice_info_thirdTv)
    TextView outWhTitle;
    @BindView(R.id.common_letter_of_notice_info_showThirdValue)
    TextView outWhName;//移出仓库
    @BindView(R.id.common_letter_of_notice_info_fourthTv)
    TextView inWhTitle;
    @BindView(R.id.common_letter_of_notice_info_showFourthValue)
    TextView inWhName;//移入仓库

    @BindView(R.id.materail_detail_ly)
    RelativeLayout materieInfoLayout;
    @BindView(R.id.common_materiel_position_info_showFirstValue)
    TextView showMaterielFirstValue;//物料编码
    @BindView(R.id.common_materiel_position_info_showSecondValue)
    TextView showMaterielSecondValue;//物料名称
    @BindView(R.id.common_materiel_position_info_showThirdValue)
    TextView showMaterielThirdValue;//总数
    @BindView(R.id.common_materiel_position_info_fourthTv)
    TextView materielFourthTv;
    @BindView(R.id.common_materiel_position_info_showFourthValue)
    TextView showMaterielFourthValue;//未定位数量、已定位数量

    private MoveDetailBean moveDetailBean;
    private ArrayList<WorkInfoBean> notJobInfo;//未作业信息
    private ArrayList<WorkInfoBean> hasJobInfo;//已作业信息
    boolean isWorkDone = false;

    int currentSelectedMaterielPosition=0;//当前物料选中的item位置
    int currentSelectedWorkPosition=0;//当前作业列表选中的item位置
    int itemConunt=-1;

    ArrayList<WorkNotesBean> remarks ;
    /**
     * 物料列表
     */
    CommonNormalAdapter materielAdapter;
    int materielAdapterFlag;
    List<BaseItemBean> itemMaterielList;

    /**
     * 作业列表
     */
    CommonNormalAdapter workAdapter;
    List<BaseItemBean> itemList;
    int workAdapterFlag;

    OrderInAndOutBoundBean orderInAndOutBoundBean;
    private String orderDetailId="";
    private String totalWeight = "";//总吨数

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_normal_detail_main;
    }

    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        showLeftBack();
        setTitleShow("移库发货详情");
        orderTitle.setText("移库单号");
        creteTimeTitle.setText("建单时间：");
        moveTypeTitle.setText("移库类型：");
        outWhTitle.setText("移出仓库：");
        inWhTitle.setText("移入仓库：");
        addNewPositionBtn.setVisibility(View.GONE);
        batchPositionBtn.setText("添加新作业");

        setRightHomeClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, "home");
            }
        });

        setRightScanClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, "scan");
                Utils.startScanActivity(MoveHouseSendGoodsDetailActivity.this);
            }
        });
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
        loadTipFailedLayout.setRestartOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMoveDetail();
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        InterfaceUtil.getInstance().setInterfaceCallBackListener(interfacesCallBackListener);
    }
    InterfaceUtil.InterfacesCallBackListener  interfacesCallBackListener=new InterfaceUtil.InterfacesCallBackListener() {
        @Override
        public void onSuccess(BaseInfo<?> baseInfo, Enum opertateFlagEnum) {
            if (opertateFlagEnum== OperateFlagEnum.NOTICE_JOB_DETAIL_FOR_SAVE_WORK){//保存作业
                ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, "保存成功");
            }else if(opertateFlagEnum==OperateFlagEnum.MOVER_DELETE_WORK){//删除
                ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, "删除成功");
            }
            moveDetailBean = null;
            itemList.clear();
            itemMaterielList.clear();
            notJobInfo.clear();
            hasJobInfo.clear();
            remarks.clear();
            isWorkDone = false;
            isHadLocation(isWorkDone);
            getMoveDetail();
        }

        @Override
        public void onFailure(String message, Enum opertateFlagEnum) {
            ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, message);
        }

        @Override
        public void onSuccess(BaseInfo<?> baseInfo) {

        }

        @Override
        public void onFailure(String message) {

        }
    };
    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        orderInAndOutBoundBean = (OrderInAndOutBoundBean) getIntent().getSerializableExtra("OrderInAndOutBoundBean");
        activityFlag = getIntent().getIntExtra(Constants.FLAG_ACTIVITY_KEY, Constants.FLAG_ACTIVITY_IN_BOUND_LOCATION_UI);

        itemMaterielList = new ArrayList<>();
        itemList = new ArrayList<>();
        notJobInfo = new ArrayList<>();
        hasJobInfo = new ArrayList<>();
        remarks = new ArrayList<>();


        notLocatedTv.setText("未作业");
        hadLocatedTv.setText("已作业");

        isWorkDone = false;
        isHadLocation(isWorkDone);

        materielAdapterFlag = CommonNormalAdapter.FLAG_NOTICE_OUT_BOUND_DETAILS_MATREIEL_MAIN;
        workAdapterFlag = CommonNormalAdapter.FLAG_NOTICE_OUT_BOUND_DETAILS_WORK_MAIN;

        getMoveDetail();


    }

    @Override
    protected void initRecyclerView() {

        /**
         * 物料列表
         */
        RecyclerViewUtil.initLinearLayoutHorizontal(this, materielRecyclerView);
        materielAdapter = CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.materiel_position_info_item, itemList, materielAdapterFlag);
        materielAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showNoOrHadWorkInfo(position);
            }
        });
        materielRecyclerView.setAdapter(materielAdapter);

        /**
         * 作业列表
         */
        RecyclerViewUtil.initLinearLayoutVERTICAL(this, workRecyclerView);
        workAdapter= CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.work_info_item, itemList, workAdapterFlag);
        /**
         * 作业列表item点击事件
         * 删除点击、保存作业点击
         */
        workAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                currentSelectedWorkPosition=position;
                singleLocationItemClick(position, view);
            }
        });
        workRecyclerView.setAdapter(workAdapter);

    }

    @OnClick({R.id.un_location_tv, R.id.located_tv, R.id.add_location_tv, R.id.location_lot_tv})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.un_location_tv://未作业
                isWorkDone=false;
                isHadLocation(isWorkDone);
                dealWorkData(notJobInfo);
                showNoOrHadWorkInfo(0);
                break;
            case R.id.located_tv://已作业
                isWorkDone = true;
                isHadLocation(isWorkDone);
                dealWorkData(hasJobInfo);
                showNoOrHadWorkInfo(0);
                break;
            case R.id.location_lot_tv://添加新作业
                itemConunt++;
                addWorkItem(itemConunt);
                break;
        }
    }

    /**
     * 是否作业
     *
     * @param isLocation
     */
    private void isHadLocation(boolean isLocation) {
        if (!isLocation) {
            notLocatedLineView.setVisibility(View.VISIBLE);
            hadLocatedLineView.setVisibility(View.INVISIBLE);
            batchPositionBtn.setVisibility(View.VISIBLE);
            notLocatedTv.setTextColor(getResources().getColor(R.color.blue));
            hadLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));
        } else {
            hadLocatedLineView.setVisibility(View.VISIBLE);
            notLocatedLineView.setVisibility(View.INVISIBLE);
            batchPositionBtn.setVisibility(View.VISIBLE);
            hadLocatedTv.setTextColor(getResources().getColor(R.color.blue));
            notLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));
        }
    }

    /**
     * 获取移库发货详情
     */
    private void getMoveDetail() {
        loadTipFailedLayout.setLoadText(R.string.since_help_loading);
        loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_PROGRESS);
        HttpManger httpManger = HttpManger.getInstance();
        httpManger.setContext(this);
        httpManger.getMoveHouseSendGoodsOrderDetail(orderInAndOutBoundBean.orderId);
        httpManger.setHttpResponseCallBackListener(new HttpManger.HttpResponseCallBackListener() {
            @Override
            public void onSuccess(BaseInfo<?> baseInfo) {
                moveDetailBean = (MoveDetailBean) baseInfo.getData();
                if (moveDetailBean != null) {
                    /**
                     * 移库发货详情基础信息
                     */
                    loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FINISH);
                    orderNo.setText(moveDetailBean.orderNo);
                    orderStatesName.setText(orderInAndOutBoundBean.displayOrderStatusName);
                    moveTypeName.setText(orderInAndOutBoundBean.orderTypeName);
                    creteTime.setText(StringUtils.isEmpty(String.valueOf(moveDetailBean.addTime)) ? ""
                            : DateUtils.getSimpleDateTimeByMill(String.valueOf(moveDetailBean.addTime), DateUtils.DATE_TIME_FORMAT));
                    outWhName.setText(moveDetailBean.outWhName);
                    inWhName.setText(moveDetailBean.inWhName);

                    /**
                     * 未作业数据
                     */
                    if (moveDetailBean.getNotJobInfo()!=null){
                        notJobInfo.addAll(moveDetailBean.getNotJobInfo());
                        if (notJobInfo.size()>0){
                            for (int i=0; i<notJobInfo.size(); i++){
                                if (i==0){
                                    notJobInfo.get(i).isSelected=true;
                                }else {
                                    notJobInfo.get(i).isSelected=false;
                                }
                            }
                        }
                    }
                    /**
                     * 已作业数据
                     */
                    if (moveDetailBean.getHasJobInfo()!=null){
                        hasJobInfo.addAll(moveDetailBean.getHasJobInfo());
                        if (hasJobInfo.size()>0){
                            for (int i=0; i<hasJobInfo.size(); i++){
                                if (i==0){
                                    hasJobInfo.get(i).isSelected=true;
                                }else {
                                    hasJobInfo.get(i).isSelected=false;
                                }
                            }
                        }
                    }
                    dealWorkData(notJobInfo);
                    showNoOrHadWorkInfo(0);
                    rs.scrollTo(0,0);

                } else {
                    loadTipFailedLayout.setTextColor(R.color.color_gray);
                    loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
                    loadTipFailedLayout.setNormalText(R.string.noMessage);
                    loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_NORMAL);
                }


            }


            @Override
            public void onFailure(String message) {
                loadTipFailedLayout.setTextColor(R.color.color_gray);
                loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                loadTipFailedLayout.setNormalText(R.string.since_help_load_failed);
                loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FAILED);
                ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, message);
            }
        });
    }


    /**
     * 处理未作业、已作业列表数据（物料）
     * @param materielWorkInfoBeanList
     */
    private void dealWorkData(ArrayList<WorkInfoBean> materielWorkInfoBeanList){
        itemMaterielList.clear();
        if (materielWorkInfoBeanList.size() > 0) {
            for (WorkInfoBean workInfoBean : materielWorkInfoBeanList) {
                itemMaterielList.add(new BaseItemBean(workInfoBean));
            }
            setWorkUIIsShow(true);
            if(!isWorkDone){
                batchPositionBtn.setVisibility(View.VISIBLE);
            }else{
                batchPositionBtn.setVisibility(View.GONE);
            }

        } else {
            setWorkUIIsShow(false);
            batchPositionBtn.setVisibility(View.GONE);
        }
        materielAdapter.setNewData(itemMaterielList);
    }

    /**
     * 处理未作业物料item点击后，对应的作业数据
     * @param positionInfoList
     */
    private void dealPositionData(ArrayList<PositionInfoBean> positionInfoList){
        itemList.clear();
        if (positionInfoList.size()>0){
            for (PositionInfoBean positionInfoBean: positionInfoList){
                itemList.add(new BaseItemBean(positionInfoBean));
            }
            workAdapter.setNewData(itemList);
            itemConunt = itemList.size();
        }else {
            itemConunt = 1;
            addWorkItem(itemConunt);
        }
        workRecyclerView.setVisibility(View.VISIBLE);
    }

    /**
     * 处理已作业物料item点击后，对应的作业数据
     * @param jobInfoBeanList
     */
    private void dealJobInfoData(ArrayList<JobInfoBean> jobInfoBeanList){
        itemList.clear();
        if (jobInfoBeanList.size()>0){
            for (JobInfoBean jobInfoBean: jobInfoBeanList){
                itemList.add(new BaseItemBean(jobInfoBean));
            }
            workAdapter.setNewData(itemList);
            itemConunt = itemList.size();

        }else {
            itemConunt = 1;
            addWorkItem(itemConunt);
        }
        workRecyclerView.setVisibility(View.VISIBLE);
    }

    /**
     * 展示当前未作业或者已作业信息
     * @param currentPosition
     */
    private void showNoOrHadWorkInfo(int currentPosition){
        if (itemMaterielList.size()<=0){
            return;
        }
        WorkInfoBean workInfoBean = (WorkInfoBean) itemMaterielList.get(currentPosition).object;
        if (workInfoBean!=null){
            orderDetailId = workInfoBean.orderDetailId;
            showMaterielFirstValue.setText(workInfoBean.skuCode);
            showMaterielSecondValue.setText(workInfoBean.skuName);
            totalWeight = workInfoBean.detailWeight+"";
            showMaterielThirdValue.setText(workInfoBean.detailAmount+"件/"+workInfoBean.detailWeight+"吨");
            if(!isWorkDone){
                showMaterielFourthValue.setText(workInfoBean.notJobAmount+"件/"+workInfoBean.notJobWeight+"吨");
            }else{
                showMaterielFourthValue.setText(workInfoBean.jobAmount+"件/"+workInfoBean.jobWeight+"吨");
            }

        }

        for (BaseItemBean baseItemBean : itemMaterielList){
            ((WorkInfoBean)baseItemBean.object).isSelected=false;
        }

        ((WorkInfoBean) itemMaterielList.get(currentPosition).object).isSelected=true;
        materielAdapter.setNewData(itemMaterielList);
        if (!isWorkDone){
            materielFourthTv.setText(getResourcesString(R.string.notWorkingNumber));
            if (workInfoBean!=null && workInfoBean.getPositionInfoList()!=null){
                dealPositionData(workInfoBean.getPositionInfoList());
            }else {
                workRecyclerView.setVisibility(View.INVISIBLE);
            }
        }else {
            materielFourthTv.setText(getResourcesString(R.string.hasWorkingNumber));
            if (workInfoBean!=null && workInfoBean.getJobInfoList()!=null){
                dealJobInfoData(workInfoBean.getJobInfoList());
            }else {
                workRecyclerView.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 设置未作业、已作业模块是否展示
     * @param isHasData
     */
    private void setWorkUIIsShow(boolean isHasData){
        if (isHasData){
            materielRecyclerView.setVisibility(View.VISIBLE);
            materieInfoLayout.setVisibility(View.VISIBLE);
            workRecyclerView.setVisibility(View.VISIBLE);
        }else {
            materielRecyclerView.setVisibility(View.GONE);
            materieInfoLayout.setVisibility(View.GONE);
            workRecyclerView.setVisibility(View.GONE);
        }
    }


    /**
     * 单个物料item下定位列表的item上点击事件
     * 未作业模块（单个保存作业操作）
     * @param tempCurrentSelectedWorkPosition 当前作业列表点击item的position
     * @param view
     */
    private void singleLocationItemClick(int tempCurrentSelectedWorkPosition, View view) {
        EditText edtShowNumberForPiece = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showNumberForPieceTv);
        EditText edtShowWeightForTon = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showWeightForTonTv);
        EditText edtShowVolumeForSquare = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showVolumeForSquareTv);
        EditText edtShowRemark = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showRemarksTv);
        //当前选中的物料item对象
        WorkInfoBean currentMaterielPositionInfoBean = (WorkInfoBean) itemMaterielList.get(currentSelectedMaterielPosition).object;

        String ids="";
        SaveJobInfoDetailRequest saveJobInfoDetailRequest = new SaveJobInfoDetailRequest();
        saveJobInfoDetailRequest.orderId = orderInAndOutBoundBean.orderId;
        saveJobInfoDetailRequest.orderNo = orderInAndOutBoundBean.orderNo;
        saveJobInfoDetailRequest.skuId = currentMaterielPositionInfoBean.skuId;
        saveJobInfoDetailRequest.skuCode = currentMaterielPositionInfoBean.skuCode;
        saveJobInfoDetailRequest.skuName = currentMaterielPositionInfoBean.skuName;

        BaseItemBean baseItemBean = itemList.get(tempCurrentSelectedWorkPosition);
        if (!isWorkDone){
            PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
            positionInfoBean.orderDetailId = orderDetailId;
            saveJobInfoDetailRequest.orderDetailId = positionInfoBean.orderDetailId;
            saveJobInfoDetailRequest.actualStockId = positionInfoBean.actualStockId;
            saveJobInfoDetailRequest.actualWhId = positionInfoBean.whId;
            saveJobInfoDetailRequest.invId = positionInfoBean.id;
            saveJobInfoDetailRequest.packageWeight = positionInfoBean.packageWeight;
            saveJobInfoDetailRequest.actualAmount = positionInfoBean.actualAmount;
            saveJobInfoDetailRequest.actualWeight = positionInfoBean.actualWeight;
            saveJobInfoDetailRequest.actualVolume = positionInfoBean.actualVolume;
            saveJobInfoDetailRequest.stockStatus = positionInfoBean.stockStatus;
            saveJobInfoDetailRequest.stockType = positionInfoBean.stockType;
            saveJobInfoDetailRequest.unitId = positionInfoBean.unitId;
            saveJobInfoDetailRequest.batchNo = positionInfoBean.batchNo;
            saveJobInfoDetailRequest.setJobAmountList(positionInfoBean.getJobAmountList());
            saveJobInfoDetailRequest.setJobAttachList(positionInfoBean.getJobAttachList());
        }else {
            JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
            saveJobInfoDetailRequest.orderDetailId = jobInfoBean.orderDetailId;
            saveJobInfoDetailRequest.noticeOrderDetailId = jobInfoBean.noticeOrderDetailId;
            saveJobInfoDetailRequest.noticeOrderId = jobInfoBean.noticeOrderId;
            saveJobInfoDetailRequest.noticeOrderNo = jobInfoBean.noticeOrderNo;
            saveJobInfoDetailRequest.actualStockId = jobInfoBean.actualStockId;
            saveJobInfoDetailRequest.invId = jobInfoBean.invId;
            saveJobInfoDetailRequest.actualWhId = jobInfoBean.actualWhId;
            saveJobInfoDetailRequest.packageWeight = jobInfoBean.packageWeight;
            saveJobInfoDetailRequest.actualAmount = jobInfoBean.actualAmount;
            saveJobInfoDetailRequest.actualWeight = jobInfoBean.actualWeight;
            saveJobInfoDetailRequest.actualVolume = jobInfoBean.actualVolume;
            saveJobInfoDetailRequest.stockStatus = jobInfoBean.stockStatus;
            saveJobInfoDetailRequest.stockType = jobInfoBean.stockType;
            saveJobInfoDetailRequest.unitId = jobInfoBean.unitId;
            saveJobInfoDetailRequest.batchNo = jobInfoBean.batchNo;
            saveJobInfoDetailRequest.remark = jobInfoBean.remark;
            ids=jobInfoBean.id;
            saveJobInfoDetailRequest.id = ids;
            saveJobInfoDetailRequest.setJobAmountList(jobInfoBean.getJobAmountList());
            saveJobInfoDetailRequest.setJobAttachList(jobInfoBean.getJobAttachList());
        }
        /**
         * 保存当前item编辑的数量、重量、体积数据。防止在编辑完后，选择库存状态、
         * 库存类型等其他操作返回到当前界面时，编辑的数据被刷新至初始数据
         */
        if (!isWorkDone){
            PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
            positionInfoBean.amount = positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
            positionInfoBean.weight = positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
            positionInfoBean.volume = positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
        }else {
            JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
            jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
            jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
            jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
            jobInfoBean.amount = new BigDecimal(edtShowNumberForPiece.getText().toString());
            jobInfoBean.weight = new BigDecimal(edtShowWeightForTon.getText().toString());
            jobInfoBean.volume = new BigDecimal(edtShowVolumeForSquare.getText().toString());
        }

        Intent intent = null;
        int reqCode = -1;
        switch (view.getId()){
            case R.id.work_info_item_sureWorkBtn://确认该作业
                /**
                 * ids为空时，该item无数据，为新加的item
                 */
                if (!isWorkDone){
                    PositionInfoBean positionInfoBean= (PositionInfoBean) baseItemBean.object;
                    positionInfoBean.amount = positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
                    positionInfoBean.weight = positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
                    positionInfoBean.volume = positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
                }else {
                    JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
                    jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
                    jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
                    jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
                    jobInfoBean.amount = new BigDecimal(edtShowNumberForPiece.getText().toString());
                    jobInfoBean.weight = new BigDecimal(edtShowWeightForTon.getText().toString());
                    jobInfoBean.volume = new BigDecimal(edtShowVolumeForSquare.getText().toString());
                }
                if (StringUtils.isEmpty(saveJobInfoDetailRequest.actualStockId)){
                    ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, getResourcesString(R.string.toastPleaseSeletedStockPosition));
                    return;
                }
                if (StringUtils.isEmpty(saveJobInfoDetailRequest.actualWhId)){
                    ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, getResourcesString(R.string.toastPleaseSeletedWareHouse));
                    return;
                }

                if (checkNumberIsEmpty(edtShowNumberForPiece, getResourcesString(R.string.toastNumberNotEmpty))){
                    return;
                }
                if (checkNumberIsEmpty(edtShowWeightForTon, getResourcesString(R.string.toastWeightNotEmpty))){
                    return;
                }
               /* if (checkNumberIsEmpty(edtShowVolumeForSquare, getResourcesString(R.string.toastVolumeNotEmpty))){
                    return;
                }*/

                if (checkNumberIsMoreThanZero(edtShowNumberForPiece, getResourcesString(R.string.toastNumberMustMoreThanZero))){
                    return;
                }
                if (checkNumberIsMoreThanZero(edtShowWeightForTon, getResourcesString(R.string.toastWeightMustMoreThanZero))){
                    return;
                }
                /*if (checkNumberIsMoreThanZero(edtShowVolumeForSquare, getResourcesString(R.string.toastVolumeMustMoreThanZero))){
                    return;
                }*/
//                }
                //获取当前提交时的数量、重量、体积值
                saveJobInfoDetailRequest.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
                saveJobInfoDetailRequest.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
                saveJobInfoDetailRequest.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
                saveJobInfoDetailRequest.remark = edtShowRemark.getText().toString().trim();
                InterfaceUtil.getInstance().saveJobNoticeBoundDetail(saveJobInfoDetailRequest, OperateFlagEnum.NOTICE_JOB_DETAIL_FOR_SAVE_WORK,
                        MoveHouseSendGoodsDetailActivity.this, isWorkDone);
                break;
            case R.id.work_info_item_workDeleteTv://删除该作业
                if (StringUtils.isEmpty(ids)){//此时该item无数据，为新增的item，故直接将列表item删除即可，无需调用接口
                    itemConunt--;
                    itemList.remove(tempCurrentSelectedWorkPosition);
                    workAdapter.setNewData(itemList);
                    return;
                }
                InterfaceUtil.getInstance().deleteMoveHouseGoodsWork(ids, OperateFlagEnum.MOVER_DELETE_WORK,
                        MoveHouseSendGoodsDetailActivity.this);
                break;
            case R.id.work_info_item_showReservoirPositionTv://库位选择
                intent = new Intent(this, DepotSelectActivity.class);
                reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT;
                startActivityForResult(intent, reqCode);
                break;
            case R.id.work_info_item_showJobRecordTv://作业记录
                remarks = saveJobInfoDetailRequest.getJobAmountList();
                intent = new Intent(this, OperateRemarkActivity.class);
                intent.putExtra("OperateRemark",remarks);
                intent.putExtra("TotolWeight",totalWeight);
                startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_JOB_RECORD);
                break;
        }

    }

    /**
     * 添加新作业数据
     * @param itemConunt 当前列表item的总数
     */
    public void addWorkItem(final int itemConunt) {
        /**
         * 设置当前添加itemView的位置，从0开始计算，故position=itemConunt-1
         */
        final int position = itemConunt-1;
        if (!isWorkDone){
            PositionInfoBean positionInfoBean=new PositionInfoBean();
            positionInfoBean.amount = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.weight = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.volume = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString("0");
            positionInfoBean.packageWeight = BigDecimalUtil.getBigDecimalByString("0");
            itemList.add(position, new BaseItemBean(positionInfoBean));
        }else {
            JobInfoBean jobInfoBean = new JobInfoBean();
            jobInfoBean.amount = BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.weight=BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.volume= BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString("0");
            jobInfoBean.packageWeight = BigDecimalUtil.getBigDecimalByString("0");
            itemList.add(position, new BaseItemBean(jobInfoBean));
        }
        workRecyclerView.smoothScrollToPosition(position);
        workAdapter.setNewData(itemList);
        workRecyclerView.setVisibility(View.VISIBLE);
        workAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == HEAD_ABLUME | requestCode == HEAD_CAREAM){
            switch (requestCode){
                case HEAD_ABLUME://相册返回
                    // 判断手机版本，因为在4.4版本都手机处理图片返回的方法就不一样了
                    //4.4以后返回的不是真实的uti而是一个封装过后的uri 所以要对封装过后的uri进行解析
                    if (data!=null){
                        if (Build.VERSION.SDK_INT >= 19) {
                            //4.4系统一上用该方法解析返回图片
                            displayImage(handleImageOnKitKat(data));
                        } else {
                            //4.4一下用该方法解析图片的获取
                            displayImage(handleImageBeforeKitKat(data));
                        }
                    }
                    break;
                case HEAD_CAREAM://相机
                    if (data != null){
                        Bundle bundle = data.getExtras();
                        if (bundle != null){//照相后，点击取消时，该bundle为空
                            Bitmap bitmap = (Bitmap) bundle.get("data");
                            String fileName = FileUtils.saveImage(bitmap);//保存照相的图片
                            Uri uri = Uri.fromFile(FileUtils.getFile(fileName));
                            displayImage(FileUtils.getRealFilePathToUri(MoveHouseSendGoodsDetailActivity.this, uri));
                        }
                    }
                    break;
            }
            return;
        }

        BaseItemBean baseItemBean = itemList.get(currentSelectedWorkPosition);
        /**
         * 获取作业记录数据
         */
        if (data != null && requestCode == AppConfig.BaseDataAction.REQCODE_JOB_RECORD) {
          remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");
            if (remarks.size() > 0) {
                String workNoteName = "";
                for (int i = 0; i < remarks.size(); i++) {
                    if (StringUtils.isBlank(workNoteName))
                        workNoteName = remarks.get(i).getDepart();
                    else
                        workNoteName = workNoteName + "," + remarks.get(i).getDepart();
                }
                if (!isWorkDone){
                    PositionInfoBean positionInfoBean= (PositionInfoBean) baseItemBean.object;
                    positionInfoBean.jobRecord = workNoteName;
                    positionInfoBean.setJobAmountList(remarks);
                    baseItemBean.object = positionInfoBean;
                }else {
                    JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
                    jobInfoBean.jobRecord = workNoteName;
                    jobInfoBean.setJobAmountList(remarks);
                    baseItemBean.object = jobInfoBean;
                }
                workAdapter.notifyItemChanged(currentSelectedWorkPosition);
            }
            return;
        }
        /**
         * 获取库存状态、库存类型等数据
         */
        if (data == null || data.getSerializableExtra("selectBean") == null)
            return;
        switch (requestCode){
            case AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT:
                SearchStockBean searchStockBean= (SearchStockBean) data.getSerializableExtra("selectBean");
                if (!isWorkDone){
                    PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
                    positionInfoBean.id = searchStockBean.getId();
                    positionInfoBean.actualStockId = searchStockBean.getStockId();
                    positionInfoBean.whId = searchStockBean.getWhId();
                    positionInfoBean.stockId = searchStockBean.getStockId();
                    positionInfoBean.stockName = searchStockBean.getStockName();
                    positionInfoBean.whId = searchStockBean.getWhId();
                    positionInfoBean.whName = searchStockBean.getWhName();
                    positionInfoBean.packageWeight = BigDecimalUtil.getBigDecimalByString(searchStockBean.getPackageWeight());
                    positionInfoBean.stockStatus = searchStockBean.getStockStatus();
                    positionInfoBean.stockStatusName = searchStockBean.getStockStatusName();
                    positionInfoBean.stockTypeName = searchStockBean.getStockTypeName();
                    positionInfoBean.stockType = searchStockBean.getStockType();
                    positionInfoBean.unitId = searchStockBean.getUnitId();
                    positionInfoBean.unitName = searchStockBean.getUnitName();
                    positionInfoBean.batchNo = searchStockBean.getBatchNo();
                    baseItemBean.object = positionInfoBean;
                }else {
                    JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
                    jobInfoBean.id = searchStockBean.getId();
                    jobInfoBean.actualStockId = searchStockBean.getStockId();
                    jobInfoBean.stockId = searchStockBean.getStockId();
                    jobInfoBean.stockName = searchStockBean.getStockName();
                    jobInfoBean.whId = searchStockBean.getWhId();
                    jobInfoBean.whName = searchStockBean.getWhName();
                    jobInfoBean.packageWeight = BigDecimalUtil.getBigDecimalByString(searchStockBean.getPackageWeight());
                    jobInfoBean.stockStatus = searchStockBean.getStockStatus();
                    jobInfoBean.stockStatusName = searchStockBean.getStockStatusName();
                    jobInfoBean.stockTypeName = searchStockBean.getStockTypeName();
                    jobInfoBean.stockType = searchStockBean.getStockType();
                    jobInfoBean.unitId = searchStockBean.getUnitId();
                    jobInfoBean.unitName = searchStockBean.getUnitName();
                    jobInfoBean.batchNo = searchStockBean.getBatchNo();
                    baseItemBean.object = jobInfoBean;
                }
                workAdapter.notifyItemChanged(currentSelectedWorkPosition);
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 校验数量、重量、体积是否为空
     * @param editText
     * @param message
     */
    private boolean checkNumberIsEmpty(EditText editText, String message){
        if (StringUtils.isEmpty(editText.getText().toString())){
            ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, message);
            return true;
        }
        return false;
    }

    /**
     * 校验数量、重量、体积是否大于0
     * @param editText
     * @param message
     */
    private boolean checkNumberIsMoreThanZero(EditText editText, String message){
        if (Float.parseFloat(editText.getText().toString())<=0){
            ToastUtil.showToast(MoveHouseSendGoodsDetailActivity.this, message);
            return true;
        }
        return false;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(final EventBusImage eventBusImage){
        currentSelectedWorkPosition=eventBusImage.currentItemPosition;
        openAblumeOrCaream(eventBusImage.flag);
    }

    /**
     * 打开相册或者相机
     * @param flag
     */
    private void openAblumeOrCaream(int flag){
        switch (flag){
            case HEAD_ABLUME://相册
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, HEAD_ABLUME);
                break;
            case HEAD_CAREAM://相机
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(camera, HEAD_CAREAM);
                break;
        }
    }

    /**
     * 通过imagepath来绘制immageview图像
     *
     * @param imagPath
     */
    protected void displayImage(String imagPath) {
        if (imagPath != null) {
            JobAttachBean jobAttachBean = new JobAttachBean();
            jobAttachBean.attachUrl = imagPath;
            ArrayList<JobAttachBean> imageList = new ArrayList<>();
            imageList.add(jobAttachBean);
            BaseItemBean baseItemBean=itemList.get(currentSelectedWorkPosition);
            if (!isWorkDone){
                PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
                positionInfoBean.imagePath = imagPath;
                positionInfoBean.setJobAttachList(imageList);
                baseItemBean.object = positionInfoBean;
            }else {
                JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
                jobInfoBean.setJobAttachList(imageList);
                jobInfoBean.imagePath = imagPath;
                baseItemBean.object = jobInfoBean;
            }
            workAdapter.notifyItemChanged(currentSelectedWorkPosition);
        } else {
            ToastUtil.showToast(this, "图片获取失败");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}












